<template>
  <view class="hospital-add-container">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">创建医院信息</text>
      <text class="page-subtitle">单一医院系统 - 请填写医院基本信息以开始使用</text>
    </view>

    <view class="form-container">
      <!-- 基本信息 -->
      <view class="form-section">
        <view class="section-header">
          <text class="section-icon">📋</text>
          <text class="section-title">基本信息</text>
          <text class="section-badge required-badge">必填</text>
        </view>
        
        <view class="form-item">
          <text class="form-label required">医院名称</text>
          <uni-easyinput 
            v-model="formData.hospital_name"
            placeholder="例如：阳光口腔医院"
            :maxlength="100"
            :clearable="true"
            trim="all"
          />
          <text v-if="errors.hospital_name" class="error-text">{{ errors.hospital_name }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">医院地址</text>
          <uni-easyinput 
            v-model="formData.address"
            placeholder="例如：北京市朝阳区XX路XX号"
            :clearable="true"
            trim="all"
          />
          <text v-if="errors.address" class="error-text">{{ errors.address }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">联系电话</text>
          <uni-easyinput 
            v-model="formData.phone"
            type="tel"
            placeholder="手机号/固话，例如：13812345678 或 010-12345678"
            :clearable="true"
            trim="all"
            @blur="validatePhone"
          />
          <text class="form-hint">支持手机号（11位）或固定电话（带区号）</text>
          <text v-if="errors.phone" class="error-text">{{ errors.phone }}</text>
        </view>

        <view class="form-item">
          <text class="form-label">医院介绍</text>
          <textarea 
            v-model="formData.introduction" 
            class="form-textarea" 
            placeholder="请输入医院简介、特色服务、医疗团队等信息，将在患者端展示"
            maxlength="1000"
          />
          <view class="char-count">{{ formData.introduction.length }}/1000</view>
        </view>
      </view>

      <!-- 图片信息 -->
      <view class="form-section">
        <view class="section-header">
          <text class="section-icon">🖼️</text>
          <text class="section-title">品牌形象</text>
          <text class="section-badge optional-badge">可选</text>
        </view>
        
        <view class="form-item">
          <text class="form-label">医院Logo</text>
          <text class="form-hint">用于应用图标和品牌标识，建议尺寸：200x200像素</text>
          <uni-file-picker 
            v-model="logoFileList"
            file-mediatype="image"
            mode="grid"
            :limit="1"
            :auto-upload="false"
            @select="handleLogoSelect"
            @delete="handleLogoDelete"
          />
        </view>
      </view>

      <!-- 营业信息 -->
      <view class="form-section">
        <view class="section-header">
          <text class="section-icon">🕐</text>
          <text class="section-title">营业信息</text>
          <text class="section-badge optional-badge">可选</text>
        </view>
        
        <view class="time-picker-group">
          <view class="form-item half">
            <text class="form-label">营业开始时间</text>
            <picker mode="time" :value="formData.working_hours_start" @change="onStartTimeChange">
              <view class="picker-view">
                <text class="picker-text">{{ formData.working_hours_start || '08:00' }}</text>
              </view>
            </picker>
          </view>

          <view class="form-item half">
            <text class="form-label">营业结束时间</text>
            <picker mode="time" :value="formData.working_hours_end" @change="onEndTimeChange">
              <view class="picker-view">
                <text class="picker-text">{{ formData.working_hours_end || '18:00' }}</text>
              </view>
            </picker>
          </view>
        </view>

        <view class="form-item">
          <text class="form-label">每周休息日</text>
          <view class="checkbox-group">
            <label v-for="(day, index) in weekDays" :key="index" class="checkbox-item">
              <checkbox 
                :value="day.value" 
                :checked="formData.closed_days.includes(day.value)"
                @tap="toggleClosedDay(day.value)"
                color="#3b82f6"
              />
              <text class="checkbox-text">{{ day.label }}</text>
            </label>
          </view>
          <text class="form-hint">选择每周固定休息的日期</text>
        </view>

        <view class="form-item">
          <text class="form-label">法定节假日</text>
          <radio-group @change="onHolidayClosedChange" class="radio-group">
            <label class="radio-item">
              <radio 
                value="true" 
                :checked="formData.holiday_closed === true"
                color="#3b82f6"
              />
              <text class="radio-text">节假日休息</text>
            </label>
            <label class="radio-item">
              <radio 
                value="false" 
                :checked="formData.holiday_closed === false"
                color="#3b82f6"
              />
              <text class="radio-text">节假日营业</text>
            </label>
          </radio-group>
          <text class="form-hint">是否在国家法定节假日休息</text>
        </view>

        <view class="form-item">
          <text class="form-label">停车信息</text>
          <uni-easyinput 
            v-model="formData.parking_info"
            placeholder="例如：地下停车场，2小时免费"
            :clearable="true"
            trim="all"
          />
        </view>

        <view class="form-item">
          <text class="form-label">公交信息</text>
          <uni-easyinput 
            v-model="formData.public_transport"
            placeholder="例如：地铁1号线XX站，公交318路"
            :clearable="true"
            trim="all"
          />
        </view>
      </view>

      <!-- 证照信息 -->
      <view class="form-section">
        <view class="section-header">
          <text class="section-icon">📄</text>
          <text class="section-title">证照信息</text>
          <text class="section-badge optional-badge">可选</text>
        </view>
        
        <view class="form-item">
          <text class="form-label">营业执照号（统一社会信用代码）</text>
          <uni-easyinput 
            v-model="formData.business_license"
            placeholder="18位，例如：91110000XXXXXXXXXX"
            :maxlength="18"
            :clearable="true"
            trim="all"
            @blur="validateBusinessLicense"
          />
          <text class="form-hint">格式：18位，由数字和大写字母组成（不含I、O、Z、S、V）</text>
          <text v-if="errors.business_license" class="error-text">{{ errors.business_license }}</text>
        </view>

        <view class="form-item">
          <text class="form-label">医疗机构执业许可证号</text>
          <uni-easyinput 
            v-model="formData.medical_license"
            placeholder="15位，例如：1101A123456789X"
            :maxlength="15"
            :clearable="true"
            trim="all"
            @blur="validateMedicalLicense"
          />
          <text class="form-hint">格式：15位，前4位数字+1位字母+9位数字+1位数字或字母</text>
          <text v-if="errors.medical_license" class="error-text">{{ errors.medical_license }}</text>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="form-actions">
        <button class="btn btn-cancel" @click="handleCancel">
          <text class="btn-icon">✕</text>
          <text>取消</text>
        </button>
        <button class="btn btn-primary" @click="handleSubmit">
          <text class="btn-icon">✓</text>
          <text>创建医院</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'

const logoFileList = ref([])

const formData = reactive({
  hospital_name: '',
  address: '',
  phone: '',
  introduction: '',
  logo: '',
  working_hours_start: '08:00',
  working_hours_end: '18:00',
  closed_days: [],
  holiday_closed: true,
  parking_info: '',
  public_transport: '',
  business_license: '',
  medical_license: ''
})

const errors = reactive({
  hospital_name: '',
  address: '',
  phone: '',
  business_license: '',
  medical_license: ''
})

// 证照和电话格式验证正则表达式
const USCI_REGEX = /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/
const MEDICAL_LICENSE_REGEX = /^\d{4}[A-Z]\d{9}[0-9A-Z]$/
// 电话号码正则：支持手机号、固话（带区号）、400电话等
const PHONE_REGEX = /^(?:(?:\+|00)86)?1[3-9]\d{9}$|^(?:(?:\d{3,4}-)?\d{7,8})$|^(?:400-?\d{7})$/

const weekDays = [
  { value: '周一', label: '周一' },
  { value: '周二', label: '周二' },
  { value: '周三', label: '周三' },
  { value: '周四', label: '周四' },
  { value: '周五', label: '周五' },
  { value: '周六', label: '周六' },
  { value: '周日', label: '周日' }
]

function onStartTimeChange(e) {
  formData.working_hours_start = e.detail.value
}

function onEndTimeChange(e) {
  formData.working_hours_end = e.detail.value
}

function toggleClosedDay(value) {
  const index = formData.closed_days.indexOf(value)
  if (index > -1) {
    formData.closed_days.splice(index, 1)
  } else {
    formData.closed_days.push(value)
  }
}

function onHolidayClosedChange(e) {
  formData.holiday_closed = e.detail.value === 'true'
}

function handleLogoSelect(e) {
  if (e.tempFiles && e.tempFiles.length > 0) {
    logoFileList.value = e.tempFiles
  }
}

function handleLogoDelete(e) {
  logoFileList.value = []
}

async function uploadImageToCloud(file, folder) {
  try {
    const uploadResult = await uniCloud.uploadFile({
      filePath: file.path,
      cloudPath: `${folder}/${Date.now()}_${Math.random().toString(36).substr(2, 9)}.${file.name.split('.').pop()}`
    })
    // 返回符合数据库 file 类型的对象结构
    return {
      bsonType: 'file',
      fileMediaType: 'image',
      url: uploadResult.fileID
    }
  } catch (err) {
    console.error('图片上传失败:', err)
    throw err
  }
}

// 验证电话号码
function validatePhone() {
  if (!formData.phone) {
    errors.phone = '请输入联系电话'
    return false
  }
  
  const value = formData.phone.trim()
  
  // 检查是否包含中文或特殊字符（只允许数字、+、-）
  if (/[\u4e00-\u9fa5]/.test(value)) {
    errors.phone = '电话号码不能包含中文'
    return false
  }
  
  if (!/^[0-9+\-]+$/.test(value)) {
    errors.phone = '电话号码只能包含数字、+、-'
    return false
  }
  
  if (!PHONE_REGEX.test(value)) {
    errors.phone = '电话号码格式不正确（支持手机号或固话）'
    return false
  }
  
  errors.phone = ''
  return true
}

// 验证统一社会信用代码
function validateBusinessLicense() {
  if (!formData.business_license) {
    errors.business_license = ''
    return true
  }
  
  const value = formData.business_license.trim().toUpperCase()
  
  if (value.length !== 18) {
    errors.business_license = '统一社会信用代码必须为18位'
    return false
  }
  
  if (!USCI_REGEX.test(value)) {
    errors.business_license = '格式错误：应为18位数字和大写字母（不含I、O、Z、S、V）'
    return false
  }
  
  errors.business_license = ''
  formData.business_license = value
  return true
}

// 验证医疗机构执业许可证号
function validateMedicalLicense() {
  if (!formData.medical_license) {
    errors.medical_license = ''
    return true
  }
  
  const value = formData.medical_license.trim().toUpperCase()
  
  if (value.length !== 15) {
    errors.medical_license = '医疗机构执业许可证号必须为15位'
    return false
  }
  
  if (!MEDICAL_LICENSE_REGEX.test(value)) {
    errors.medical_license = '格式错误：前4位数字+1位字母+9位数字+1位数字或字母'
    return false
  }
  
  errors.medical_license = ''
  formData.medical_license = value
  return true
}

function validateForm() {
  let isValid = true
  
  if (!formData.hospital_name || formData.hospital_name.trim().length === 0) {
    errors.hospital_name = '请输入医院名称'
    isValid = false
  } else {
    errors.hospital_name = ''
  }
  
  if (!formData.address || formData.address.trim().length === 0) {
    errors.address = '请输入医院地址'
    isValid = false
  } else {
    errors.address = ''
  }
  
  // 验证电话号码
  if (!validatePhone()) {
    isValid = false
  }
  
  // 验证证照号（如果已填写）
  if (formData.business_license && !validateBusinessLicense()) {
    isValid = false
  }
  
  if (formData.medical_license && !validateMedicalLicense()) {
    isValid = false
  }
  
  return isValid
}

async function handleSubmit() {
  if (!validateForm()) {
    uni.showToast({ title: '请检查表单错误', icon: 'none' })
    return
  }
  
  try {
    // 🔒 单一医院系统限制：检查是否已存在医院
    uni.showLoading({ title: '检查中...' })
    const hospitalService = uniCloud.importObject('dh-hospital-service')
    const checkResult = await hospitalService.checkHospitalExists()
    
    if (checkResult.code === 200 && checkResult.data.exists) {
      uni.hideLoading()
      uni.showModal({
        title: '系统提示',
        content: '系统仅支持单一医院，已存在医院记录。请前往医院列表编辑现有医院信息。',
        showCancel: false,
        success: () => {
          uni.redirectTo({ url: '/pages/business/hospitals/list' })
        }
      })
      return
    }
    
    uni.showLoading({ title: '提交中...' })
    
    let logoData = null
    if (logoFileList.value && logoFileList.value.length > 0) {
      try {
        uni.showLoading({ title: '上传Logo中...' })
        logoData = await uploadImageToCloud(logoFileList.value[0], 'hospitals/logos')
      } catch (uploadErr) {
        uni.hideLoading()
        uni.showToast({ title: 'Logo上传失败', icon: 'none' })
        return
      }
    }
    
    const db = uniCloud.database()
    const submitData = {
      hospital_name: formData.hospital_name,
      address: formData.address,
      phone: formData.phone,
      introduction: formData.introduction,
      working_hours_start: formData.working_hours_start,
      working_hours_end: formData.working_hours_end,
      closed_days: formData.closed_days,
      holiday_closed: formData.holiday_closed,
      parking_info: formData.parking_info,
      public_transport: formData.public_transport,
      business_license: formData.business_license,
      medical_license: formData.medical_license
    }
    
    // 如果有logo，添加file对象；否则不添加该字段
    if (logoData) {
      submitData.logo = logoData
    }
    
    console.log('提交数据:', submitData)
    
    // 调用云对象方法创建医院
    const hospitalsObj = uniCloud.importObject('dh-hospitals')
    const result = await hospitalsObj.createHospital(submitData)
    
    uni.hideLoading()
    
    // 判断创建是否成功
    if (result.code === 201 && result.data && result.data._id) {
      uni.showToast({ title: result.message || '创建成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/business/hospitals/list' })
      }, 1500)
    } else {
      console.error('创建失败，返回结果:', result)
      uni.showToast({ title: '创建失败：未获取到记录ID', icon: 'none' })
    }
  } catch (err) {
    console.error('========== 创建医院失败 ==========')
    console.error('完整错误对象:', err)
    console.error('错误类型:', typeof err)
    console.error('错误构造函数:', err.constructor?.name)
    
    uni.hideLoading()
    
    // 提取详细错误信息
    let errorMessage = '创建失败'
    let errorDetails = ''
    
    try {
      // 尝试多种方式提取错误信息
      if (err.message) {
        errorMessage = err.message
        console.error('err.message:', err.message)
      }
      
      if (err.errMsg) {
        errorDetails = err.errMsg
        console.error('err.errMsg:', err.errMsg)
      }
      
      if (err.errCode) {
        console.error('err.errCode:', err.errCode)
      }
      
      if (err.code) {
        console.error('err.code:', err.code)
      }
      
      // 如果有详细错误信息
      if (err.detail) {
        console.error('err.detail:', JSON.stringify(err.detail, null, 2))
        errorDetails = JSON.stringify(err.detail)
      }
      
      // 如果是对象，尝试序列化
      if (typeof err === 'object') {
        console.error('错误对象keys:', Object.keys(err))
        console.error('错误对象JSON:', JSON.stringify(err, Object.getOwnPropertyNames(err), 2))
      }
      
      // 组合最终错误消息
      if (errorDetails && errorDetails !== errorMessage) {
        errorMessage = `${errorMessage}\n详情: ${errorDetails}`
      }
      
    } catch (parseErr) {
      console.error('解析错误信息失败:', parseErr)
    }
    
    console.error('最终错误消息:', errorMessage)
    console.error('====================================')
    
    uni.showToast({ 
      title: errorMessage.length > 50 ? errorMessage.substring(0, 50) + '...' : errorMessage, 
      icon: 'none',
      duration: 4000 
    })
    
    // 如果错误信息太长，额外显示模态框
    if (errorMessage.length > 50) {
      setTimeout(() => {
        uni.showModal({
          title: '详细错误信息',
          content: errorMessage,
          showCancel: false
        })
      }, 500)
    }
  }
}

function handleCancel() {
  uni.showModal({
    title: '确认取消',
    content: '取消后将返回医院列表，已填写的信息将不会保存',
    success: (res) => {
      if (res.confirm) {
        uni.redirectTo({ url: '/pages/business/hospitals/list' })
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.hospital-add-container {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20rpx;
}

/* 页面标题 */
.page-header {
  background: #fff;
  padding: 32rpx 40rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #1f2937;
  display: block;
  margin-bottom: 8rpx;
}

.page-subtitle {
  font-size: 26rpx;
  color: #6b7280;
  display: block;
}

/* 表单容器 */
.form-container {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.form-section {
  padding: 40rpx;
  border-bottom: 1rpx solid #e5e7eb;
  
  &:last-child {
    border-bottom: none;
  }
}

/* 分区标题 */
.section-header {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 32rpx;
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid #e5e7eb;
}

.section-icon {
  font-size: 32rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #1f2937;
  flex: 1;
}

.section-badge {
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  font-weight: 500;
  
  &.required-badge {
    background: #fee2e2;
    color: #991b1b;
  }
  
  &.optional-badge {
    background: #e0f2fe;
    color: #075985;
  }
}

/* 表单项 */
.form-item {
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &.half {
    flex: 1;
  }
}

.time-picker-group {
  display: flex;
  gap: 24rpx;
}

.form-label {
  font-size: 28rpx;
  color: #374151;
  display: block;
  margin-bottom: 16rpx;
  font-weight: 500;
  
  &.required::after {
    content: ' *';
    color: #ef4444;
  }
}

.form-hint {
  font-size: 24rpx;
  color: #6b7280;
  display: block;
  margin-bottom: 12rpx;
  line-height: 1.5;
}

.form-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #d1d5db;
  border-radius: 12rpx;
  box-sizing: border-box;
  background: #ffffff;
  line-height: 1.6;
  
  &:focus {
    border-color: #3b82f6;
    outline: none;
  }
}

.char-count {
  font-size: 22rpx;
  color: #9ca3af;
  text-align: right;
  margin-top: 8rpx;
}

.picker-view {
  padding: 20rpx 24rpx;
  background: #f9fafb;
  border: 1rpx solid #d1d5db;
  border-radius: 12rpx;
  transition: all 0.2s;
  
  &:active {
    background: #f3f4f6;
    border-color: #3b82f6;
  }
}

.picker-text {
  font-size: 28rpx;
  color: #1f2937;
}

.checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.checkbox-item {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background: #f9fafb;
  border-radius: 12rpx;
  border: 1rpx solid #d1d5db;
  min-width: 140rpx;
  transition: all 0.2s;
  
  &:active {
    background: #eff6ff;
    border-color: #3b82f6;
  }
}

.checkbox-text {
  font-size: 26rpx;
  color: #374151;
  margin-left: 12rpx;
}

.radio-group {
  display: flex;
  gap: 24rpx;
  flex-wrap: wrap;
}

.radio-item {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background: #f9fafb;
  border-radius: 12rpx;
  border: 1rpx solid #d1d5db;
  min-width: 180rpx;
  transition: all 0.2s;
  
  &:active {
    background: #eff6ff;
    border-color: #3b82f6;
  }
}

.radio-text {
  font-size: 26rpx;
  color: #374151;
  margin-left: 12rpx;
}

.error-text {
  font-size: 24rpx;
  color: #ef4444;
  display: block;
  margin-top: 8rpx;
}

/* 操作按钮 */
.form-actions {
  display: flex;
  gap: 24rpx;
  padding: 40rpx;
  background: #f9fafb;
  border-top: 1rpx solid #e5e7eb;
}

.btn {
  flex: 1;
  height: 96rpx;
  border-radius: 12rpx;
  border: none;
  font-size: 32rpx;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  transition: all 0.3s ease;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
  
  &.btn-cancel {
    background: #ffffff;
    color: #6b7280;
    border: 1rpx solid #d1d5db;
    box-shadow: none;
    
    &:active {
      background: #f9fafb;
    }
  }
  
  &.btn-primary {
    background: #3b82f6;
    color: #fff;
    
    &:active {
      background: #2563eb;
      transform: translateY(2rpx);
    }
  }
}

.btn-icon {
  font-size: 28rpx;
}

/* 移动端响应式 */
@media (max-width: 768px) {
  .hospital-add-container {
    padding: 16rpx;
  }
  
  .page-header {
    padding: 24rpx 32rpx;
  }
  
  .page-title {
    font-size: 36rpx;
  }
  
  .form-section {
    padding: 32rpx;
  }
  
  .time-picker-group {
    flex-direction: column;
    gap: 0;
  }
  
  .form-item.half {
    width: 100%;
    margin-bottom: 32rpx;
  }
  
  .form-actions {
    padding: 32rpx;
    flex-direction: column;
  }
  
  .btn {
    width: 100%;
  }
}
</style>
